package com.situ.store.listener;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: LoginNumberListener
 * Package: com.situ.store.listener
 * Description:
 *
 * @Author Darling_达
 * @Create 2023-03-05 16:39
 * @Version 1.0
 */
@WebListener
public class LoginNumberListener implements HttpSessionAttributeListener {


    @Override
    @SuppressWarnings("unchecked")
    public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
        List<String> isLoginedUser = (List<String>) httpSessionBindingEvent.getSession().getServletContext().getAttribute("C");
        if (isLoginedUser == null || isLoginedUser.size() == 0) {
            isLoginedUser = new ArrayList<>();
        }
        String username = (String) httpSessionBindingEvent.getSession().getAttribute("username");
        isLoginedUser.add(username);
        httpSessionBindingEvent.getSession().setAttribute("C", isLoginedUser);
    }

    @Override
    @SuppressWarnings("unchecked")
    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
        HttpSession session = httpSessionBindingEvent.getSession();
        List<String> isLoginedUser = (List<String>) httpSessionBindingEvent.getSession().getServletContext().getAttribute("C");
        String username = (String) httpSessionBindingEvent.getSession().getAttribute("username");
        if (!"".equals(username) && username != null && isLoginedUser != null && isLoginedUser.size() > 0){
            isLoginedUser.remove(username);
        }
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {

    }
}
